﻿using System;
using ACompany.OrderProcessing.Infrastructure;
using ACompany.OrderProcessing.Infrastructure.CustomExceptions;
using ACompany.OrderProcessing.NHibernateRepository;
using NHibernate;

public class NHibernateUnitOfWork : IUnitOfWork
{
    private readonly ISession _Session;

    public NHibernateUnitOfWork()
    {
        _Session = SessionFactory.GetCurrentSession();
    }

    public void Save(IAggregateRoot Entity)
    {
        //TODO: Use CurrentSession, this will be from the HttpContext
        _Session.SaveOrUpdate(Entity);
    }


    public void Commit()
    {
        using (var transaction = _Session.BeginTransaction())
        {
            try
            {
                transaction.Commit();
                // flush the session and commit the transaction
            }
            catch (StaleObjectStateException NHex)
            {
                transaction.Rollback();
                // TODO: Log exception
                // Catch StaleObjectStateException:
                // Entity was changed while we were viewing it, 
                // Wrap Nhibernate exception  and then send it 
                // back up the calling stack 
                throw new ConcurrencyException("Please reload the screen as changes have been made to an entity since first viewing.", NHex);

            }
            catch (Exception )
            {
                transaction.Rollback();
                // TODO: Log exception
                throw;
            }

        }


    }

    public void Delete(IAggregateRoot Entity)
    {
        _Session.Delete(Entity);
    }

}